//
//  TourMapViewController.m
//  51-Tour
//
//  Created by xiang ying on 14-3-25.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "TourMapViewController.h"
#import "AudioPlayEngine.h"
#import "ServiceManage.h"
#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "amrFileCodec.h"
#import "NSString+TPCategory.h"
#import "BMKGeometry.h"
#import "db_Downloading.h"

#define AUTOPLAY_DISTANCE 30
@interface TourMapViewController ()<UIGestureRecognizerDelegate,UIScrollViewDelegate,AudioPlayEngineDelegate,BMKMapViewDelegate>{
    BasicMapAnnotation *_annotation;
    UIImageView         *bg;
    ScenicScene        *_scene;
    
    BMKMapView          *_mapView;
    float               lastScale;  //缩放
    float               _firstX ;   //移动
    float               _firstY;    //移动
    
    UIView              *playTool;
    UISlider            *progressView;
    UIButton            *playBtn;
    
    NSTimer             *progressTimer;
    
    CGFloat             height;
    CGFloat             orignY;
    
    UIView              *currentPlayed;
    
    UIImageView         *selfLoc;
 
    NSDate              *updateDate;
    
    NSMutableArray      *playHistory;
    BOOL                waitspeeking;       //等待概览诉说加载
    
    BOOL                iszooming;          // 正在放大
    
    UITapGestureRecognizer *tap;
    
    NSMutableArray      *_annationArray;
    
    BOOL                needLocate;
    
    CGFloat lastsetx,lastsety;
}

@end

@implementation TourMapViewController

-(void)dealloc{
    //
    [AudioPlayEngine instance]._delegate = nil;
    [[AudioPlayEngine instance] stopPlay:NO];
}

-(void)popself{
    [self stopTimer:YES];
    if (progressTimer) {
        [progressTimer invalidate];
        progressTimer = nil;
    }
    [selfLoc stopAnimating];
    if (_annationArray.count!=0) {
        [_mapView removeAnnotations:_annationArray];
    }
    [_mapView removeGestureRecognizer:tap];
    [AudioPlayEngine instance]._delegate = nil;
    [[AudioPlayEngine instance] stopPlay:NO];
    [super popself];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        playHistory = [NSMutableArray array];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:@"applicationDidBecomeActive" object:nil];
    }
    return self;
}

-(id)initWithAnnotation:(BasicMapAnnotation*)annotation mapView:(BMKMapView*)map{
    self = [super init];
    if (self) {
        _annotation = annotation;
        _mapView = map;
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
}

-(void)viewDidAppear:(BOOL)animated{
    if (_annotation.type == 2) {
        [_mapView setZoomLevel:_annotation.zoomScale];
        needLocate = YES;
        [self performSelector:@selector(aimMap:) withObject:nil afterDelay:1];
    }
}

- (void)loadView
{
    [super loadView];
    
    [self initNavigationItme:_annotation.title];
    
    waitspeeking = YES;
    needLocate = YES;
    [AudioPlayEngine instance]._delegate = self;

    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showToolBar:)];
    tap.delegate = self;
    [tap setNumberOfTapsRequired:1];
    [self.contentView addGestureRecognizer:tap];
    
    height = self.contentView.frame.size.height+self.contentView.frame.origin.y;
    self.contentView.frame = CGRectMake(0, 0, 320, height);

    if (_annotation.type == 2) {
        _annationArray = [NSMutableArray array];

        if (_mapView.annotations.count!=0) {
            [_annationArray addObjectsFromArray:_mapView.annotations];
            [_mapView removeAnnotations:_annationArray];
        }
        _mapView.frame = self.contentView.bounds;
        [self.contentView addSubview:_mapView];
        
        UIButton *locBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [locBtn setImage:[UIImage imageNamed:@"dw_25"] forState:UIControlStateNormal];
        [locBtn setImage:[UIImage imageNamed:@"dw-select_25"] forState:UIControlStateHighlighted];
        locBtn.frame = CGRectMake(8, self.contentView.bounds.size.height-60, 38, 38);
        [locBtn addTarget:self action:@selector(aimMap:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:locBtn];
        
    }else{
        orignY = self.contentView.frame.origin.y;
        lastScale = 1;
        lastsetx = 0;
        lastsety = 0;
        self.contentView.delegate = self;
//        [self.contentView setBouncesZoom:NO];
        [self.contentView setMinimumZoomScale:_annotation.zoomScale/2];
        [self.contentView setMaximumZoomScale:_annotation.zoomScale*1.5];
        [self.contentView setShowsHorizontalScrollIndicator:NO];
        [self.contentView setShowsVerticalScrollIndicator:NO];
        
        
    //    导游介绍地图
        bg = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
        bg.contentMode = UIViewContentModeScaleToFill;
        bg.autoresizesSubviews = NO;
        bg.userInteractionEnabled = YES;
        bg.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [self.contentView addSubview:bg];
        
    }
    
    playTool = [[UIView alloc] initWithFrame:CGRectMake(0, self.contentView.frame.origin.y+self.contentView.frame.size.height-44, 320, 44)];
    playTool.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];
    
    playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playBtn setImage:[UIImage imageNamed:@"ic-play_09"] forState:UIControlStateNormal];
    [playBtn setImage:[UIImage imageNamed:@"ic-pause_09"] forState:UIControlStateSelected];
    [playBtn setFrame:CGRectMake(10, (44-23)/2, 23, 23)];
    [playBtn addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];
    [playTool addSubview:playBtn];
    
    
    progressView = [[UISlider alloc] initWithFrame:CGRectMake(44, (44-7)/2, 232, 7)];
    [progressView setThumbImage:[UIImage imageNamed:@"sliding-point_12"] forState:UIControlStateNormal];
//    [progressView setMaximumTrackImage:[[UIImage imageNamed:@"progress-bar-bg_12"] stretchableImageWithLeftCapWidth:50 topCapHeight:0] forState:UIControlStateNormal];
//    [progressView setMinimumTrackImage:[[UIImage imageNamed:@"the-slider_12"] stretchableImageWithLeftCapWidth:10 topCapHeight:0] forState:UIControlStateNormal];
    [progressView addTarget:self action:@selector(quickplay:) forControlEvents:UIControlEventTouchUpInside];
    [playTool addSubview:progressView];
    
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"ic-quit_09"] forState:UIControlStateNormal];
    [cancelBtn setFrame:CGRectMake(320-33, (44-23)/2, 23, 23)];
    [cancelBtn addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    [playTool addSubview:cancelBtn];
    [self.view addSubview:playTool];
    
    [self initlize];
}

- (void)viewDidLoad{
    [super viewDidLoad];
}

- (void)showSvHUD:(NSNumber*)show{
    if ([show boolValue]) {
        [SVProgressHUD showWithStatus:[[DataCenter instance] getStringForKey:@"loading"]];
    }else{
        [SVProgressHUD dismiss];
    }
}

#pragma mark - backgpround methodes
//decode
- (void)decodeAmr:(NSData*)data{
    //解码需要时间
    [self performSelectorOnMainThread:@selector(showSvHUD:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO];
    _scene.data = DecodeAMRToWAVE(data);
    //
    [self performSelectorOnMainThread:@selector(showSvHUD:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];

    [self performSelectorOnMainThread:@selector(playNow:) withObject:_scene.data waitUntilDone:NO];
    //本地在线缓存
    NSString *displayname = [[NSFileManager defaultManager] displayNameAtPath:_scene.voice];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.wav",AUDIOPATH,displayname];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        //没有就写文件
        [_scene.data writeToFile:filePath atomically:YES];
    }
}

//download
//在线下载队列
-(void)downloadList{
    for (ScenicDTO *dto in _scene.scenicPoints) {
        //在线缓存
        if (dto.vtg_resource_url) {
            NSString *displayname = [[NSFileManager defaultManager] displayNameAtPath:dto.vtg_resource_url];
            NSString *filePath = [NSString stringWithFormat:@"%@/%@.wav",AUDIOPATH,displayname];
            if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                dto.data = [NSData dataWithContentsOfFile:filePath];
            }else{
                //去下载
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:dto.vtg_resource_url]];
                dto.data = DecodeAMRToWAVE(data);
                [dto.data writeToFile:filePath atomically:YES];
            }
        }
    }
}

#pragma mark -
- (void)getDataFromLocal{
    
    NSString *unzipPath = [NSString stringWithFormat:@"%@/%@_%@",UNZIPDOCUMENTPATH,_annotation.vtg_scenic_id,[[DataCenter instance] getLanguageType]==zh_cn?@"zh-cn":@"en-us"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:unzipPath]) {

        _scene = [[ScenicScene alloc] init];
        _scene.scenicId = _annotation.vtg_scenic_id;
        _scene.scenicName = _annotation.title;
        _scene.scenicPoints = [NSMutableArray array];
        
        //解析点
        NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:unzipPath error:nil];
        
        NSString *mainProperty = nil;
        
        for (NSString *file in files) {
            if ([[[NSFileManager defaultManager] displayNameAtPath:file] hasSuffix:@"png"]) {
                //底图
                mainProperty = [file stringByReplacingOccurrencesOfString:@"png" withString:@"properties"];
                _scene.sceneMap = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",unzipPath,file]];
                bg.image = _scene.sceneMap;
                [ServiceManage parseProperties:[NSString stringWithFormat:@"%@/%@",unzipPath,mainProperty] completion:^(NSInteger errCode, NSString *errorMsg, ScenicDTO *result) {
                    if (errCode == 0) {
                        _scene.top_left = result.top_left;
                        _scene.type = result.type;
                        _scene.bottom_right = result.bottom_right;
                        NSString *fileScene = [NSString stringWithFormat:@"%@/%@",unzipPath,[file stringByReplacingOccurrencesOfString:@"png" withString:@"amr"]];
                        NSData *data = [NSData dataWithContentsOfFile:fileScene];
                        if (data) {
                            [self performSelectorInBackground:@selector(decodeAmr:) withObject:data];
                        }
                        [self adduserLog:_scene.scenicId];
                    }
                }];
                break;
            }
        }
        
        for (NSString *file in files) {
            if ([[[NSFileManager defaultManager] displayNameAtPath:file] hasSuffix:@"properties"]) {
                if (![file isEqualToString:mainProperty]) {
                    [ServiceManage parseProperties:[NSString stringWithFormat:@"%@/%@",unzipPath,file] completion:^(NSInteger errCode, NSString *errorMsg, ScenicDTO *result) {
                        if (errCode == 0) {
                            if (result.type == 2) {
                                _scene.type = 2;
                                _scene.zoomScale = result.zoomScale;
                                NSString *fileScene = [NSString stringWithFormat:@"%@/%@",unzipPath,[file stringByReplacingOccurrencesOfString:@"properties" withString:@"amr"]];
                                NSData *data = [NSData dataWithContentsOfFile:fileScene];
                                if (data) {
                                    [self performSelectorInBackground:@selector(decodeAmr:) withObject:data];
                                }
                            }else{
                                [_scene.scenicPoints addObject:result];
                            }
                        }
                    }];
                }
            }
        }
        [self drawMap];
    }else{
        [self getDataFromNet];
    }
}

- (void)getDataFromNet{
    [SVProgressHUD showWithStatus:[[DataCenter instance] getStringForKey:@"loading"]];
    [ServiceManage getOnlineResourceRequestInfo:@{@"Mobile": [DataCenter instance].user.userPhone,@"LanguageId":_annotation.vtg_language_id} completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            _scene = respond.data;
            
            //本地在线缓存
            NSString *displayname = [[NSFileManager defaultManager] displayNameAtPath:_scene.voice];
            NSString *filePath = [NSString stringWithFormat:@"%@/%@.wav",AUDIOPATH,displayname];
            if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                _scene.data = [NSData dataWithContentsOfFile:filePath];
            }
            if (_scene.data) {
                [SVProgressHUD dismiss];
                [self playNow:_scene.data];
                [self adduserLog:_scene.scenicId];
            }else{
                //下载语音简介
                [ServiceManage downloadCache:_scene.voice completion:^(RespondDTO *respond) {
                    if (respond.flag == respond_receicedata) {
                        //接收到数据
                        [SVProgressHUD showProgress:[respond.data floatValue]];
                    }else if(respond.flag == respond_success){
                        [SVProgressHUD dismiss];
                        //接收完成
                        if (respond.data) {
                            [self performSelectorInBackground:@selector(decodeAmr:) withObject:respond.data];
                        }
                        [self adduserLog:_scene.scenicId];
                    }else {
                        [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"novoice"]];
                        _scene.data = nil;
                        NSLog(@"error");
                    }
                }];
            }
            [self performSelectorInBackground:@selector(downloadList) withObject:nil];
            [self drawMap];
        }else {
            [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"loadfailed"]];
            [self performSelector:@selector(popself) withObject:nil afterDelay:0.8];
        }
    }];
}

- (void)initlize{

    ScenicScene *scenic = [db_Downloading getScenic:[NSString stringWithFormat:@"%@",_annotation.vtg_scenic_id] language:[[DataCenter instance] getLanguageType]==zh_cn?@"zh-cn":@"en-us"];
    if (scenic.needUpdate||![scenic.zipFile isEqualToString:_annotation.zipurl]) {
        [self getDataFromNet];
    }else{
        [self getDataFromLocal];
    }
}

- (void)drawMap{
    if (_scene.type == 1) {
        //设置地图
        if (_scene.sceneMap) {
            bg.image = _scene.sceneMap;
        }else{
            __block UIImageView *img = bg;
            
            NSString *displayname = [[NSFileManager defaultManager] displayNameAtPath:_scene.icon];
            __block NSString *filePath = [NSString stringWithFormat:@"%@/%@.png",MAPPATH,displayname];
            if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                _scene.sceneMap = [UIImage imageWithContentsOfFile:filePath];
                bg.image = _scene.sceneMap;
            }else{
                [img setImageWithURL:[NSURL URLWithString:_scene.icon] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                    if (image) {
                        bg.image = image;
                        _scene.sceneMap = image;
                        [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
                    }else {
                        [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"guidepicerror"]];
                    }
                }];
            }
        }
        
        //绘制景点
        for (int i = 0;i<_scene.scenicPoints.count;i++) {
            ScenicDTO *dto = _scene.scenicPoints[i];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, 30, 30);
            [button setImageEdgeInsets:UIEdgeInsetsMake(7,7,7,7)];
            [button setImage:[UIImage imageNamed:@"red-point_03"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"grey-point_03"] forState:UIControlStateSelected];
            button.tag = i+100;
            [button addTarget:self action:@selector(playScenic:) forControlEvents:UIControlEventTouchUpInside];
            button.center = CGPointMake(bg.frame.size.width*(dto.GPS.x-_scene.top_left.x)/(_scene.bottom_right.x-_scene.top_left.x), bg.frame.size.height/(_scene.bottom_right.y-_scene.top_left.y)*(dto.GPS.y-_scene.top_left.y));
//            NSLog(@"%f,%f",button.center.x,button.center.y);
            [self.contentView addSubview:button];
            
            UILabel *label = [[UILabel alloc] init];//WithFrame:CGRectMake(button.frame.size.width+button.frame.origin.x, button.frame.origin.y, 120, 30)];
            label.backgroundColor = [UIColor clearColor];
            label.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLabel:)];
            [label addGestureRecognizer:tap1];
            label.font = [UIFont systemFontOfSize:12];
            label.shadowColor = [UIColor whiteColor];
            label.textColor = [UIColor blackColor];
            label.text = dto.vtg_scenic_name;
            label.frame = CGRectMake(button.frame.size.width+button.frame.origin.x-5, button.frame.origin.y, [dto.vtg_scenic_name widthwithfont:label.font height:30], 30);
            label.tag = i+200;
            [self.contentView addSubview:label];
        }
        
        [self.contentView setZoomScale:_annotation.zoomScale animated:NO];
    }else{
        [_annationArray removeAllObjects];
        for (int i = 0;i<_scene.scenicPoints.count;i++) {
            ScenicDTO *dto = _scene.scenicPoints[i];
            BasicMapAnnotation *pointAnnotation = [[BasicMapAnnotation alloc]initWithLatitude:dto.GPS.y andLongitude:dto.GPS.x];
            pointAnnotation.title = dto.vtg_scenic_name;//@"中山陵";
            pointAnnotation.vtg_language_id = dto.vtg_language_id;
            pointAnnotation.vtg_language_key = dto.vtg_language_key;
            pointAnnotation.vtg_scenic_id = dto.vtg_scenic_id;
            pointAnnotation.zipurl = dto.vtg_resource_url;
            pointAnnotation.zoomScale = _annotation.zoomScale;
            pointAnnotation.type = _annotation.type;
            pointAnnotation.tag = i+100;
            [_annationArray addObject:pointAnnotation];
        }
        if (_annationArray.count!=0) {
            [_mapView addAnnotations:_annationArray];
        }
    }

    [self showToolBar:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIScrollVieDelegate
//设置图片缩放与移动
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return bg;
    
}
// 让UIImageView在UIScrollView缩放后居中显示
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
//    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
//    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
//    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
//    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
//    
//    CGPoint center = bg.center;
//    bg.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,scrollView.contentSize.height * 0.5 + offsetY);
    
//    NSLog(@"center :%f,%f,   %f,%f",bg.center.x,bg.center.y,offsetX,offsetY);
    //绘制景点
    
    
    for (int i = 0;i<_scene.scenicPoints.count;i++) {
        UIView *button = [self.contentView viewWithTag:100+i];
        button.center = CGPointMake((button.center.x)/lastScale*scrollView.zoomScale, (button.center.y)/lastScale*scrollView.zoomScale);
        
        UIView *label = [self.contentView viewWithTag:200+i];
        label.frame = CGRectMake(button.frame.origin.x+button.frame.size.width-5, button.frame.origin.y, label.frame.size.width, label.frame.size.height);
    }
    selfLoc.center = CGPointMake(selfLoc.center.x/lastScale*scrollView.zoomScale, selfLoc.center.y/lastScale*scrollView.zoomScale);

    lastScale = scrollView.zoomScale;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {

    iszooming = YES;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    
    iszooming = NO;

}
#pragma mark - Play

void interruptionLister(void* inClientData,UInt32 inInterrutionState){
    if (inInterrutionState == kAudioSessionBeginInterruption) {
        NSLog(@"interpupr");
    }else{
        NSLog(@"end");
    }
}

- (void)audioPlayerBeginInterruption{
    [self stopTimer:YES];
//    [[AudioPlayEngine instance] pausePlay];
}

- (void)audioPlayerDidFinishPlaying:(BOOL)flag{
    [self stopTimer:YES];
    if (progressTimer) {
        [progressTimer invalidate];
        progressTimer = nil;
    }
    progressView.value = 0;
    //
    if (currentPlayed) {
        if ([currentPlayed isKindOfClass:[UIButton class]]) {
            ((UIButton*)currentPlayed).selected = NO;
            [(UIButton*)currentPlayed setImage:[UIImage imageNamed:@"green-point_03"] forState:UIControlStateNormal];
        }else{
            UIImageView *imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
            [imageView setHighlighted:NO];
            [imageView setImage:[UIImage imageNamed:@"green-point_03"]];
        }

    }
}

- (void)audioPlayerEndInterruption{
    [self stopTimer:NO];
//    [[AudioPlayEngine instance] play];
}

#pragma mark - Button Methodes
//快进
- (void)quickplay:(UISlider*)sender{
    if(![[AudioPlayEngine instance] playAttime:sender.value]){
    }
}

//点击标签播放
-(void)tapLabel:(UIGestureRecognizer*)tap1{
    [self playScenic:(UIButton*)[self.contentView viewWithTag:tap1.view.tag-100]];
}

//点击按钮播放
-(void)playScenic:(UIView*)sender{
//    播放    
    [UIView animateWithDuration:0.3 animations:^{
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        self.contentView.frame = CGRectMake(0, 0, 320, height);
        [playTool setCenter:CGPointMake(playTool.center.x, height+playTool.frame.size.height/2)];
    }];
    [sender.superview bringSubviewToFront:sender];
    
    ScenicDTO *dto = _scene.scenicPoints[[sender tag]-100];
    //缓存数据
    
    if (!dto.data) {
        NSString *unzipPath = [NSString stringWithFormat:@"%@/%@_%@",UNZIPDOCUMENTPATH,_annotation.vtg_scenic_id,[[DataCenter instance] getLanguageType]==zh_cn?@"zh-cn":@"en-us"];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:unzipPath]) {
            //离线资源(先查找amr文件，没有再查找MP3文件)
            NSString *amrfile = [NSString stringWithFormat:@"%@/%@.amr",unzipPath,dto.vtg_scenic_id];
            if ([[NSFileManager defaultManager] fileExistsAtPath:amrfile]) {
                dto.data = DecodeAMRToWAVE([NSData dataWithContentsOfFile:amrfile]);
            }else{
                dto.data = DecodeAMRToWAVE([NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.mp3",unzipPath,dto.vtg_scenic_id]]);
            }
        }else{
            //在线缓存
            if (dto.vtg_resource_url) {
                NSString *displayname = [[NSFileManager defaultManager] displayNameAtPath:dto.vtg_resource_url];
                NSString *filePath = [NSString stringWithFormat:@"%@/%@.wav",AUDIOPATH,displayname];
                if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                    dto.data = [NSData dataWithContentsOfFile:filePath];
                }
            }
        }
    }
    
    if (!dto.data) {
        dto.data = [NSData data];
        NSString *displayname = [[NSFileManager defaultManager] displayNameAtPath:dto.vtg_resource_url];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.wav",AUDIOPATH,displayname];
        [SVProgressHUD showProgress:0];
        [ServiceManage downloadCache:dto.vtg_resource_url completion:^(RespondDTO *respond) {
            if (respond.flag == respond_receicedata) {
                //接收到数据
                [SVProgressHUD showProgress:[respond.data floatValue]];
            }else if(respond.flag == respond_success){
                [SVProgressHUD dismiss];
                //接收完成
                dto.data = DecodeAMRToWAVE(respond.data);
                [dto.data writeToFile:filePath atomically:YES];
                
                if([self playNow:dto.data]){
                    if ([currentPlayed isKindOfClass:[UIButton class]]) {
                        [(UIButton*)currentPlayed setImage:[UIImage imageNamed:@"green-point_03"] forState:UIControlStateNormal];
                        currentPlayed = sender;
                        [(UIButton*)currentPlayed setImage:[UIImage imageNamed:@"red-point_03"] forState:UIControlStateNormal];
                    }else{
                        UIImageView *imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
//                        [imageView stopAnimating];
                        [imageView setHighlighted:NO];
                        [imageView setImage:[UIImage imageNamed:@"green-point_03"]];
                        currentPlayed = sender;
                        imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
                        [imageView setImage:[UIImage imageNamed:@"red-point_03"]];
//                        [imageView startAnimating];
                    }
                    
                    if (![playHistory containsObject:dto]) {
                        [playHistory addObject:dto];
                        [self adduserLog:dto.vtg_scenic_id];
                    }
                }
            }else {
                [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"loadfailed"]];
                dto.data = nil;
                NSLog(@"error");
            }
        }];
    }else{
        if([self playNow:dto.data]){
            if ([currentPlayed isKindOfClass:[UIButton class]]) {
                [(UIButton*)currentPlayed setImage:[UIImage imageNamed:@"green-point_03"] forState:UIControlStateNormal];
                currentPlayed = sender;
                [(UIButton*)currentPlayed setImage:[UIImage imageNamed:@"red-point_03"] forState:UIControlStateNormal];
            }else{
                UIImageView *imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
//                [imageView stopAnimating];
                [imageView setHighlighted:NO];
                [imageView setImage:[UIImage imageNamed:@"green-point_03"]];
                currentPlayed = sender;
                imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
                [imageView setImage:[UIImage imageNamed:@"red-point_03"]];
//                [imageView startAnimating];
            }
            if (![playHistory containsObject:dto]) {
                [playHistory addObject:dto];
                [self adduserLog:dto.vtg_scenic_id];
            }
        }
    }
}

-(void)playOrPause:(UIButton*)sender{
    if ([[AudioPlayEngine instance] isPlaying]) {
        [self stopTimer:YES];
        [[AudioPlayEngine instance] pausePlay];
    }else{
        if ([[AudioPlayEngine instance] hasData]) {
            [self stopTimer:NO];
            if ([currentPlayed isKindOfClass:[UIButton class]]) {
                [(UIButton*)currentPlayed setImage:[UIImage imageNamed:@"red-point_03"] forState:UIControlStateNormal];
            }else{
                UIImageView *imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
                [imageView setImage:[UIImage imageNamed:@"red-point_03"]];
            }
            [[AudioPlayEngine instance] play];
            [[AudioPlayEngine instance] playAttime:progressView.value];
        }
    }
}

-(void)showToolBar:(UIGestureRecognizer*)tap{
    [UIView animateWithDuration:0.3 animations:^{
        if (playTool.center.y == height+playTool.frame.size.height/2) {
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            self.contentView.frame = CGRectMake(0, orignY, 320, height);
            [playTool setCenter:CGPointMake(playTool.center.x, height-playTool.frame.size.height/2)];
        }else{
            [self.navigationController setNavigationBarHidden:YES animated:YES];
            self.contentView.frame = CGRectMake(0, 0, 320, height);
            [playTool setCenter:CGPointMake(playTool.center.x, height+playTool.frame.size.height/2)];
        }
    }];
}

-(void)cancel:(UIButton*)sender{
    [[AudioPlayEngine instance] stopPlay:YES];
}

#pragma mark -

- (void)applicationDidBecomeActive:(NSNotification *)noti{
    if (![AudioPlayEngine instance].isPlaying) {
        [self stopTimer:YES];
    }else{
        
    }
}

-(BOOL)playNow:(NSData*)data{
    NSTimeInterval time = [[AudioPlayEngine instance] playAudio:data];
    if (time!=-1) {
        progressView.maximumValue = time;
        waitspeeking = NO;
        [self stopTimer:NO];
        return YES;
    }
    return NO;
}

-(void)stopTimer:(BOOL)yesOrno{
    if (yesOrno) {
//        if (progressTimer) {
//            [progressTimer invalidate];
//            progressTimer = nil;
//        }
    }else{
        if (![progressTimer isValid]) {
            progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(progressUpdate) userInfo:nil repeats:YES];
        }
    }

    playBtn.selected = !yesOrno;
    progressView.enabled = !yesOrno;
}

-(void)progressUpdate{
    [progressView setValue:[[AudioPlayEngine instance] getCurrentPlayTime] animated:NO];
    if (currentPlayed) {
        if ([currentPlayed isKindOfClass:[UIButton class]]) {
            ((UIButton*)currentPlayed).selected = !((UIButton*)currentPlayed).selected;
        }else{
            
            UIImageView *imageView = (UIImageView*)[currentPlayed viewWithTag:1098];
            [imageView setHighlighted:!imageView.isHighlighted];
//            if (!imageView.isAnimating) {
//                [imageView startAnimating];
//            }
        }
    }
}


#pragma mark - 添加记录
-(void)adduserLog:(NSString*)scenicId{
    NSDictionary *dic = @{@"ScenicId":scenicId,@"Mobile":[DataCenter instance].user.userPhone};
    [ServiceManage addUserlogRequestInfo:dic completion:^(RespondDTO *respond) {
        //
        NSLog(@"add user log %@",respond.msg);
    }];
}

#pragma mark - 定位

- (void)autoplayBylocaton:(CLLocation*)location{
    
    if (![[AudioPlayEngine instance] isPlaying]&&!waitspeeking) {
        //定位计算距离自动播放
        CLLocationDistance minmeters = AUTOPLAY_DISTANCE;
        int                j = 0;
        for (int i= 0;i<_scene.scenicPoints.count;i++) {
            
            ScenicDTO *dto = _scene.scenicPoints[i];
            if (![playHistory containsObject:dto]) {
                //不在播放历史里的讲解点进行自动播放
                // 计算距离
                BMKMapPoint point1 = BMKMapPointForCoordinate(location.coordinate);
                BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(dto.GPS.y, dto.GPS.x));
                
                CLLocationDistance meters = BMKMetersBetweenMapPoints(point1,point2);
                if (meters<minmeters) {
                    minmeters = meters;
                    j = i;
                }
            }
        }
        if (minmeters<AUTOPLAY_DISTANCE) {
            //自动播放符合条件的最近的点
            if (_annotation.type == 1) {
                [self playScenic:[self.contentView viewWithTag:j+100]];
            }else{
                [self playScenic:[_mapView viewWithTag:j+100]];
            }
        }
    }

    if (_annotation.type == 1) {
        if (!waitspeeking&&!iszooming) {
            if (!selfLoc) {
                selfLoc = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
                selfLoc.image = [UIImage imageNamed:@"icon_center_point"];
                [selfLoc setAnimationImages:@[[UIImage imageNamed:@"icon_center_point"],[UIImage imageNamed:@"icon_center_point30"]]];
                [selfLoc setAnimationDuration:1];
                [selfLoc startAnimating];
                [self.contentView addSubview:selfLoc];
            }
            
            [self.contentView bringSubviewToFront:selfLoc];
            
            selfLoc.center = CGPointMake(self.contentView.contentSize.width*(location.coordinate.longitude-_scene.top_left.x)/(_scene.bottom_right.x-_scene.top_left.x), self.contentView.contentSize.height/(_scene.bottom_right.y-_scene.top_left.y)*(location.coordinate.latitude-_scene.top_left.y));
            
            //    if (CGRectContainsPoint(bg.frame,selfLoc.center)) {
            [self.contentView scrollRectToVisible:CGRectMake(selfLoc.center.x-160, selfLoc.center.y-self.contentView.frame.size.height/2, 320, self.contentView.frame.size.height) animated:YES];
            //    }
            
            if (selfLoc.center.x<0||selfLoc.center.y<0||selfLoc.center.x>self.contentView.contentSize.width||selfLoc.center.y>self.contentView.contentSize.height) {
                selfLoc.hidden = YES;
            }else{
                selfLoc.hidden = NO;
            }
        }
    }
}

/**
 *用户位置更新后，会调用此函数
 *@param mapView 地图View
 *@param userLocation 新的用户位置
 */

- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
	if (userLocation != nil) {
        if (_annotation.type == 2) {
            if (needLocate) {
//                [mapView setCenterCoordinate:userLocation.location.coordinate];
                needLocate = NO;
            }
        }
        if (updateDate) {
            NSTimeInterval seconds = [updateDate timeIntervalSinceNow];
            if (-seconds>3) {
                updateDate = [NSDate date];
                [self autoplayBylocaton:userLocation.location];
            }
        }else{
            updateDate = [NSDate date];
            [self autoplayBylocaton:userLocation.location];
        }
    }
}


#pragma mark - BMKMapViewDelegate
-(IBAction)aimMap:(id)sender{
    [_mapView setCenterCoordinate:_mapView.userLocation.location.coordinate animated:YES];
}

/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewWillStartLocatingUser:(BMKMapView *)mapView
{
	NSLog(@"start locate");
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

// 根据anntation生成对应的View

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSString *AnnotationViewID = @"voiceMark";
    BMKAnnotationView *newAnnotation = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (!newAnnotation) {
        newAnnotation = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        // 设置不可拖拽
        newAnnotation.draggable = NO;
//        newAnnotation.backgroundColor = [UIColor redColor];
        [newAnnotation setFrame:CGRectMake(0, 0, 45, 21)];
        
        newAnnotation.paopaoView = nil;
        
        newAnnotation.exclusiveTouch = YES;
        newAnnotation.autoresizesSubviews = YES;
        
        
        UIImageView *papo = [[UIImageView alloc] initWithFrame:CGRectMake(0, 3, 15, 15)];
        papo.tag = 1098;
//        papo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [papo setImage:[UIImage imageNamed:@"red-point_03"]];
        [papo setHighlightedImage:[UIImage imageNamed:@"grey-point_03"]];
        [newAnnotation addSubview:papo];
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 30, 21)];
        label.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        label.layer.borderWidth = 1;
        label.layer.cornerRadius = 4;
        label.layer.borderColor = BORDERCOLOR.CGColor;
        label.font = [UIFont boldSystemFontOfSize:12];
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        label.tag = 345;
        label.textAlignment = NSTextAlignmentCenter;
        [newAnnotation addSubview:label];
        
    }
    [newAnnotation setAnnotation:annotation];
    
    UILabel *label = (UILabel*)[newAnnotation viewWithTag:345];
    label.text = annotation.title;
    CGFloat width = [annotation.title widthwithfont:label.font height:label.frame.size.height];
    newAnnotation.frame = CGRectMake(0, 0, width+20, newAnnotation.frame.size.height);
    newAnnotation.tag = [(BasicMapAnnotation*)annotation tag];
    newAnnotation.centerOffset = CGPointMake((newAnnotation.frame.size.width/2-7.5), 0);

    return newAnnotation;
    
}

- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view{
    
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    [mapView deselectAnnotation:view.annotation animated:YES];
    if (view.annotation!=mapView.userLocation) {
        [self playScenic:view];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isKindOfClass:[BMKAnnotationView class]]) {
        return NO;
    }
    
    return YES;
}

@end
